package com.baidu.iit.pvm.runtime;

import com.baidu.iit.pvm.PvmException;
import com.baidu.iit.pvm.delegate.ActivityBehavior;
import com.baidu.iit.pvm.process.ActivityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 节点的动作执行类，当进入节点时触发
 *
 * @ThreadSafe
 *
 * Created by 卫立 on 2014/4/7.
 */
public class AtomicOperationActivityExecute implements AtomicOperation {

    private static Logger logger = LoggerFactory.getLogger(AtomicOperationActivityExecute.class);

    public boolean isAsync(InterpretableExecution execution) {
        return false;
    }

    public void execute(InterpretableExecution execution) {
        ActivityImpl activity = (ActivityImpl) execution.getActivity();

        ActivityBehavior activityBehavior = activity.getActivityBehavior();

        if (activityBehavior == null) {
            throw new PvmException("在 节点 {} 中没有配置相关的动作 " + activity);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("{} executes {}: {}", execution, activity, activityBehavior.getClass().getName());
        }
        try {
            //执行具体的动作
            //大部分的系统具体的调度机制在这个类里面实现
            activityBehavior.execute(execution);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new PvmException(" activity <" + activity.getProperty("type") + " id=\"" + activity.getId() + "\" ...>: " + e.getMessage(), e);
        }
    }
}
